
import json
import paho.mqtt.client as mqtt
from sensor_info_table_methods import SensorInfoTableMethods
from settings import *
import threading
import logging

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')

logger = logging.getLogger(__name__)

# 定义连接回调函数
def on_connect(client, userdata, flags, rc):
    logger.info(f"Connected with result code {rc}")
    # 订阅主题
    client.subscribe(MQTT_TOPIC_SUBSCRIBE, qos=1)
    # 连接成功后发布一条消息
    # client.publish("test/topic", "Hello from Python via MQTT!")

def on_message(client, userdata, msg):

    logger.info(f"Received message on topic {msg.topic}: {msg.payload.decode()}")
    # 处理消息
    msg = msg.payload.decode()
    # msg 格式如下:{"type": "senorInfo", "data": {"devaddr": 1, "text": "e51c07f000120d6d002101011950000001000000005000010100605b", "parse_data": {"start_character": "e5", "len": 28, "sn": 2032, "command_type": "sensor_info", "devaddr": "120d", "rssi": 109, "date": "2000-1-1 1:19:50", "dev_type": "\u538b\u529b", "sensor_value": {"pressure_value ": 0.0}, "battery_percentage": "80 %", "sensor_light": "00", "firmware_version": "01", "hardware_version": "01", "number_of_abnormal": "00", "abnormals": ""}}}
    # 调用 SensorInfoTableMethods 类中的 insert_sensor_info_to_db 方法插入数据
    with SensorInfoTableMethods() as db:
        try:
            # 解析数据
            msg = json.loads(msg)
            # 调用 insert_sensor_data 方法插入数据
            sensor_info = db.insert_sensor_data(msg["data"]["text"])

        except Exception as e:


            logger.error(f"Error data: {msg}")
            logger.error(f"Error: {e}")

        else:
            # 向 WebSocket 推送数据
            result = client.publish(WEB_SOCKET_TOPIC, json.dumps(sensor_info), qos=1)

            if result[0] == 0:
                logger.info(f"Published message to topic {WEB_SOCKET_TOPIC}: {json.dumps(sensor_info)}")
            else:
                logger.error(f"Failed to publish message to topic {WEB_SOCKET_TOPIC}: {json.dumps(sensor_info)}")


def run_mqtt_service():

    # 创建 MQTT 客户端实例
    client = mqtt.Client()

    # 设置连接回调函数
    client.on_connect = on_connect

    # 设置消息接收回调函数
    client.on_message = on_message

    # 连接到 Mosquitto 的标准 MQTT 端口
    client.connect("localhost", 1883, 60)

    # 启动网络循环
    client.loop_forever()

def run_mqtt_service_in_thread():

    threading.Thread(target=run_mqtt_service).start()


if __name__ == '__main__':

    run_mqtt_service()

